import os
import uuid
from django.utils import timezone as datetime
from django.core import serializers
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from lxml import etree
from bamboo.models import User,Article,Art_comment
from django.core.mail import send_mail
import random
from mysite import settings
import collections

# Create your views here.

@csrf_exempt
def upload_image(request):
    allow_suffix = ['jpg', 'png', 'jpeg', 'gif', 'bmp']
    files = request.FILES.get("imgFile", None)
    if files:
        file_suffix = files.name.split(".")[-1]
        if file_suffix not in allow_suffix:
            return JsonResponse({"error": 1, "message": "图片格式不正确"})
        file_name = str(uuid.uuid1()) + "." + file_suffix
        # file_path = os.path.join(settings.MEDIA_ROOT, 'image', file_name)  # TODO:上传的路径需要修改#图片位置修改
        # url_path = os.path.join(settings.MEDIA_URL, 'image', file_name)#图片位置修改
        file_path = os.path.join(settings.MEDIA_ROOT, file_name)  # TODO:上传的路径需要修改
        url_path = os.path.join(settings.MEDIA_URL, file_name)
        with open(file_path, 'wb') as f:
            f.write(files.file.read())
        return JsonResponse({"error": 0, "url": url_path})


def loginPage(request):

    return JsonResponse({'name':'lanbaba'})

# 登录处理
def to_index(request):
    response = {}
    response['url'] = "/fail404"
    if (request.method == 'POST'):
        print('-----------')
        result = json.loads(request.body)
        username = result.get('username')
        password = result.get('password')
        user = User.objects.filter(username=username,password=password).first()
        # print(username,password)
        if user:
            print(user.pk)
            response['user_name'] = username
            response['user_id'] = user.pk
            response['url'] = "/indexPage"
    return JsonResponse(response)

# 注册处理
def register(request):
    res = {}
    if (request.method == 'POST'):
        result = json.loads(request.body)
        print(result)
        username = result.get('username')
        password = result.get('password')
        email = result.get('email')
        phone = result.get('phone')
        ress = User.objects.create(username=username,password=password,email=email,phone=phone)
        res['url'] = '/loginPage'
    else:
        res['url'] = "/fail404"
    print(res)
    return JsonResponse(res)

# 注册验证
def checkUsername(request):
    response = {}
    if(request.method=='POST'):
        result = json.loads(request.body)
        username = result.get('username')
        user = User.objects.filter(username=username)
        if user:
            response['caseOne'] = True
        else:
            response['caseOne'] = False
    return JsonResponse(response)

#初始化首页数据
def index_load_data(request):
    response = {}
    if (request.method == 'POST'):
        result = json.loads(request.body)
        art_id = result.get('art_id')
        if art_id == None:
            art_id = False
    response['articles'] = getArticle(art_id)
    # response['u_name'] = request.session['u_name']
    # print(response.get('articles'))
    return JsonResponse(response)

#处理文章列表
def getArticle(art_id):

    article_list = []
    if art_id:
        article = Article.objects.filter(pk=art_id)
        articles = article.values("id", 'title','comment','fabulous','author_id','mod_date','content','article_views')
    else:
        articles = Article.objects.values("id", 'title','comment','fabulous','author_id','mod_date','content','article_views')
    for artic in articles:
        article = {}
        article['id'] = artic.get('id')
        article['title'] = artic.get('title')
        article['comment'] = artic.get('comment')
        article['fabulous'] = artic.get('fabulous')
        article['article_views'] = artic.get('article_views')
        article['author'] = User.objects.filter(id = artic.get('author_id'))[0].username
        article['mod_date'] = artic.get('mod_date').strftime('%Y-%m-%d %H:%M:%S')
        # 更改图片显示路径
        article['content'] = artic.get('content').replace(r'/upload_image/',r'/static/images/')
        #首页显示简介
        article['cl_content'] = cl_content(artic.get('content'))
        # 添加到列表
        if art_id:
            return article
        else:
            article_list.append(article)
    # print('------------获取成功！---------------')
    return article_list

#处理文章内容
def cl_content(content):
    html = etree.HTML(content)
    content = ''.join(html.xpath("//p/text()"))
    return content

#邮箱验证
def ver_email(request):
    receive_list = []
    ver_code = ''
    for i in range(6):
        ver_code = ver_code+str(random.randint(0,9))
    title = 'XXXX博客系统验证'
    mesg = '您好，验证码为：{}'.format(ver_code)

    if (request.method == 'POST'):
        result = json.loads(request.body)
        email = result.get('email')
        receive_list.append(email)
    send_mail(
        title,
        mesg,
        'a17623010185@163.com',
        receive_list,
        fail_silently=False
    )
    print(ver_code)
    if len(receive_list)>0:
        return JsonResponse({
            'vercode':ver_code,
            'case':True,
        })
    else:
        return JsonResponse({
            'case': False,
        })
# send_mail的参数分别是  邮件标题，邮件内容，发件箱(settings.py中设置过的那个)，收件箱列表(可以发送给多个人),失败静默(若发送失败，报错提示我们)
# send_mail('Subject here', 'Here is the message.', 'charleschen@xmdaren.com',['to@example.com'], fail_silently=False)

#分页
#list（Artcile.objects.all()[start:end）]

#点赞
def dianzan(request):
    response = {}
    if (request.method == 'POST'):
        result = json.loads(request.body)
        art_id = result.get('art_id')
        zan_type = result.get('art_type')
        art = Article.objects.filter(pk=art_id)[0]
        # print(zan_type)
        if zan_type==1:
            art.fabulous += 1
            art.save()
        else:
            art.fabulous -= 1
            art.save()

    response['fabulous'] = art.fabulous
    # response['u_name'] = request.session['u_name']
    # print(response.get('articles'))
    return JsonResponse(response)

#寻找子评论
def tree_search(d_dic, comment_obj):
    # 在comment_dic中一个一个的寻找其回复的评论
    # 检查当前评论的 reply_id 和 comment_dic中已有评论的nid是否相同，
    # 如果相同，表示就是回复的此信息
    #   如果不同，则需要去 comment_dic 的所有子元素中寻找，一直找，如果一系列中未找，则继续向下找
    #d_dic为文章一级评论
    for k, v in d_dic.items():
        # print(str(comment_obj.send_obj.id)+'发送对象')
        # 找回复的评论，将自己添加到其对应的字典中，例如： {评论一： {回复一：{},回复二：{}}}
        if comment_obj.send_obj.id==k:
            res = User.objects.filter(pk=comment_obj.user_id.id).first()
            d_dic[k]['send_obj'].append({
                'art_id': comment_obj.id,
                'com_user_name': res.username,
                'content': comment_obj.content,
                'send_obj': {},
                'com_time': comment_obj.com_time.strftime('%Y-%m-%d %H:%M')
            })
        # else:
        #     # 在当前第一个跟元素中递归的去寻找父亲
        #     tree_search({k:v}, comment_obj)
    return d_dic

def build_tree(com_list,com_list_all):
    comment_dic = {}
    art_result = {}
    # 文章的第一级评论
    for com in com_list:
        res = User.objects.filter(pk=com.user_id.id).first()
        comment_dic[com.id] = {
            'art_id':com.id,
            'com_user_name':res.username,
            'content':com.content,
            'send_obj': [],
            'com_time':com.com_time.strftime('%Y-%m-%d %H:%M')
    }
    #数据库所有评论
    for comment_obj in com_list_all:
        if comment_obj.art_id is not None:
            # print(comment_obj.content)
            pass
        else:
            # 如果是回复的评论，则需要在 comment_dic 中找到其回复的评论
            art_results = tree_search(comment_dic, comment_obj)
    return art_results

#获取评论列表
def get_art_comments(request):
    art_id = ''
    if (request.method == 'POST'):
        result = json.loads(request.body)
        art_id = result.get('art_id')
        # print(art_id)
        com_list = Art_comment.objects.filter(art_id=art_id)#文章一级评论
        com_list_all = Art_comment.objects.all()#所有评论
        art_results = build_tree(com_list,com_list_all)
        print(len(art_results))
        if len(art_results)==0:
            return HttpResponse('NONE')
    return HttpResponse(json.dumps(art_results))

#写评论
def write_comments(request):
    art_id = ''
    send_obj = ''
    response = {
        'com':'this is com',
    }
    if (request.method == 'POST'):
        result = json.loads(request.body)
        user_id = User.objects.filter(pk=int(result.get('user_id')))[0]
        art_id = result.get('art_id')
        send_obj = result.get('send_obj')
        art_content = result.get('art_content')
        art_time = datetime.datetime.now()
        if result.get('art_id')=='':
            art_id = None
        else:
            art_id = Article.objects.filter(pk=int(art_id))[0]
        if result.get('send_obj')=='':
            send_obj = None
        else:
            send_obj = Art_comment.objects.filter(pk=int(send_obj))[0]
        #
        # user_id = User.objects.filter(pk=1)[0]
        # art_id = Article.objects.filter(pk=1)[0]
        # send_obj = Art_comment.objects.filter(pk=1)[0]
        # print(type(user_id))
        com = Art_comment.objects.create(art_id=art_id,user_id=user_id,send_obj=send_obj,content=art_content,com_time=art_time)
        print(com)
        response['case'] = 'y'
    return JsonResponse(response)



























